package com.hdax.dm.common.intercetors;

import com.alibaba.fastjson.JSON;
import com.hdax.dm.utils.request.tokenutil;
import com.hdax.dm.utils.response.CommonResponse;
import com.hdax.dm.utils.response.ResponseUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

public class AuthIntherceptor implements HandlerInterceptor {


    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    public void parsertokenerr1(HttpServletResponse response) throws IOException {
        //鉴权失败后处理
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        CommonResponse commonResponse = ResponseUtil.returnFail("9999","登录超时！请重新登录");
        out.println(JSON.toJSONString(commonResponse));
    }
    public void parsertokenerr2(HttpServletResponse response) throws IOException {
        //鉴权失败后处理
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        CommonResponse commonResponse = ResponseUtil.returnFail("9999","验签失败！请重新登录");
        out.println(JSON.toJSONString(commonResponse));
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.判断是否需要鉴权
        //查看请求路径中是否包含 /p/
        if (request.getRequestURI().contains("/p/")) {
            //需要鉴权
            //2.获取请求头中的token进行鉴权
            String token = request.getHeader("token");
            try {
                Claims claims= tokenutil.parserToken(token);
                String id=claims.getId();
                Date date=claims.getIssuedAt();
                //congredis中获取token，如果无法获取就说明已经过期
                String redisToken = redisTemplate.opsForValue().get("token:"+id);

                if (redisToken==null) {
                    parsertokenerr1(response);
                    return false;
                }
                return true;
            }catch (Exception ex){
                //鉴权失败后处理
                parsertokenerr2(response);
                return false;
            }
        }else{
            //不需要鉴权
            return true;
        }
    }
}
